package win.demonlegion.quartz.job;

import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import win.demonlegion.util.RandomUtil;
import win.demonlegion.util.TimestampUtil;

import java.util.Date;

public class DemoTask implements Job {
    private static final Logger logger = LoggerFactory.getLogger(DemoTask.class);

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        logger.debug("quartz hello world!!!");
    }

    public void start(Scheduler scheduler) {
        addJob(this.getClass(), getRandomInterval(), scheduler);
    }

    protected void addJob(Class<? extends Job> jobClass, int interval, Scheduler scheduler) {
        addJob(jobClass, TimestampUtil.getDatetime(interval), scheduler);
    }

    protected void addJob(Class<? extends Job> jobClass, Date executeDate, Scheduler scheduler) {
        SimpleScheduleBuilder schedule = SimpleScheduleBuilder.simpleSchedule();
        // 定义Job
        JobDetail job =
                JobBuilder.newJob(jobClass)
                        .withIdentity("Demo", jobClass.getSimpleName())
                        .build();
        // 定义Trigger
        Trigger trigger =
                TriggerBuilder.newTrigger()
                        .withIdentity("Trigger" + jobClass.getSimpleName() + "_Demo", jobClass.getSimpleName())
                        .startAt(executeDate)
                        .withSchedule(schedule).build();
        logger.debug("将在" + TimestampUtil.formatDatetime(executeDate) + "执行");
        scheduleShuntJob(scheduler, job, trigger);
    }

    protected void scheduleShuntJob(Scheduler scheduler, JobDetail job, Trigger trigger) {
        try {
            scheduler.scheduleJob(job, trigger);
        } catch (SchedulerException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }

    private int getRandomInterval() {
        return RandomUtil.getRandomDelay(9, 9);
    }
}
